'use strict';

const Service = require('egg').Service;

class InterviewScheduleService extends Service {
  // 获取日程列表
  async findAll(options = {}) {
    const { ctx } = this;
    const { company_id, user_id, page = 1, pageSize = 5 } = options;
    
    const offset = (page - 1) * pageSize;
    const limit = parseInt(pageSize);

    // 构建查询条件
    const where = {};
    if (company_id) {
      where.company_id = company_id;
    }
    if (user_id) {
      where.user_id = user_id;
    }

    const { count, rows } = await ctx.model.InterviewSchedule.findAndCountAll({
      where,
      include: [
        {
          model: ctx.model.User,
          as: 'candidate',
          attributes: ['id', 'username', 'avatar'],
          required: false
        }
      ],
      order: [['start_time', 'ASC']],
      offset,
      limit,
    });

    // 处理返回数据，添加候选人名称
    const processedRows = rows.map(row => {
      const data = row.toJSON();
      data.candidate_name = data.candidate ? data.candidate.username : `用户${data.user_id}`;
      return data;
    });

    return {
      data: processedRows,
      pagination: {
        current: page,
        pageSize: pageSize,
        total: count,
        pages: Math.ceil(count / pageSize)
      }
    };
  }

  // 根据ID获取日程详情
  async findById(id) {
    const { ctx } = this;
    return await ctx.model.InterviewSchedule.findByPk(id);
  }

  // 创建日程
  async create(data) {
    const { ctx } = this;
    return await ctx.model.InterviewSchedule.create({
      ...data,
      created_at: new Date(),
    });
  }

  // 更新日程
  async update(id, data) {
    const { ctx } = this;
    const schedule = await ctx.model.InterviewSchedule.findByPk(id);
    if (schedule) {
      return await schedule.update(data);
    }
    return null;
  }

  // 删除日程
  async delete(id) {
    const { ctx } = this;
    const result = await ctx.model.InterviewSchedule.destroy({
      where: { schedule_id: id },
    });
    return result > 0;
  }
}

module.exports = InterviewScheduleService;
